package com.shouer.doc;

import android.content.Context;
import android.util.Log;
import android.view.View;

import com.shouer.doc.application.App;
import com.shouer.doc.common.util.AppUtil;
import com.shouer.doc.common.util.BackgroundUtil;
import com.shouer.doc.event.NewOrderEvent;
import com.shouer.doc.event.QueryUnReadCountEvent;
import com.shouer.doc.event.RongRemoteLoginEvent;
import com.shouer.doc.event.ShowAppTxtMsgMessage;
import com.shouer.doc.event.ShowOrderNotification;
import com.shouer.doc.message.AppTxtMsgMessage;
import com.shouer.doc.message.OrderMessage;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import io.rong.imkit.DefaultExtensionModule;
import io.rong.imkit.IExtensionModule;
import io.rong.imkit.RongExtensionManager;
import io.rong.imkit.RongIM;
import io.rong.imkit.model.UIConversation;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.RongIMClient.OnReceiveMessageListener;
import io.rong.imlib.location.message.RealTimeLocationStartMessage;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.CommandNotificationMessage;
import io.rong.message.ContactNotificationMessage;
import io.rong.message.ImageMessage;
import io.rong.message.InformationNotificationMessage;
import io.rong.message.LocationMessage;
import io.rong.message.ProfileNotificationMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

/**
 * Created by yangyayun on 2016/11/9.
 */

public class ShouerAppContext implements OnReceiveMessageListener, RongIM.ConversationListBehaviorListener, RongIM.ConversationBehaviorListener, RongIMClient.ConnectionStatusListener {


    private Context mContext;

    private static ShouerAppContext mRongCloudInstance;


    /**
     * 初始化 RongCloud.
     *
     * @param context 上下文。
     */
    public static void init(Context context) {

        if (mRongCloudInstance == null) {

            synchronized (ShouerAppContext.class) {

                if (mRongCloudInstance == null) {
                    mRongCloudInstance = new ShouerAppContext(context);
                }
            }
        }
    }


    public ShouerAppContext(Context mContext) {
        this.mContext = mContext;
        RongIM.registerMessageType(OrderMessage.class);
        RongIM.registerMessageType(AppTxtMsgMessage.class);
        initListener();
    }


    /**
     * init 后就能设置的监听
     */
    private void initListener() {
        RongIM.setConversationBehaviorListener(this);//设置会话界面操作的监听器。
        RongIM.setConversationListBehaviorListener(this);
        RongIM.setOnReceiveMessageListener(this);
        RongIM.setConnectionStatusListener(this);
        setInputProvider();
        setReadReceiptConversationType();
        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String s) {
                return ((App)mContext).getUserInfo(s);
            }
        },true);
        RongIM.setGroupInfoProvider(new RongIM.GroupInfoProvider() {
            @Override
            public Group getGroupInfo(String s) {
                return ((App)mContext).getGroupInfo(s);
            }
        },  true);
    }


    private void setReadReceiptConversationType() {
        Conversation.ConversationType[] types = new Conversation.ConversationType[]{
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.DISCUSSION
        };
        RongIM.getInstance().setReadReceiptConversationTypeList(types);
    }

    private void setInputProvider() {
        List<IExtensionModule> moduleList = RongExtensionManager.getInstance().getExtensionModules();
        IExtensionModule defaultModule = null;
        if (moduleList != null) {
            for (IExtensionModule module : moduleList) {
                if (module instanceof DefaultExtensionModule) {
                    defaultModule = module;
                    break;
                }
            }
            if (defaultModule != null) {
                RongExtensionManager.getInstance().unregisterExtensionModule(defaultModule);
                RongExtensionManager.getInstance().registerExtensionModule(new MyExtensionModule());
            }
        }

    }

    /**
     * 接收消息监听
     */
    @Override
    public boolean onReceived(Message message, int i) {

        if (message.getContent() instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message.getContent();
            Log.d("onReceived", "TextMesesage---收收收收--接收到一条【文字消息】-----" + textMessage.getContent() + ",getExtra:" + textMessage.getExtra());

        } else if (message.getContent() instanceof OrderMessage) {
            OrderMessage orderMessage = (OrderMessage) message.getContent();
            Log.e("onReceived", "OrderMessage---收收收收--接收到一条【订单消息】-----" + orderMessage.getContent().toString());
            if ((System.currentTimeMillis() - message.getSentTime()) < 60 * 1000) {
                if (BackgroundUtil.getRunningAppProcesses(mContext, AppUtil.getPackageName(mContext))) {
                    ShowOrderNotification showOrderNotification = new ShowOrderNotification();
                    showOrderNotification.setOrderMessage(orderMessage);
                    EventBus.getDefault().post(showOrderNotification);

                } else {
                    NotificationInterface.sendOrderNotification(mContext, orderMessage.getContent());
                }
                EventBus.getDefault().post(new NewOrderEvent());
            }
            return true;
        } else if (message.getContent() instanceof AppTxtMsgMessage){

            if (BackgroundUtil.getRunningAppProcesses(mContext, AppUtil.getPackageName(mContext)))
            {
                ShowAppTxtMsgMessage showAppTxtMsgMessage=new ShowAppTxtMsgMessage();
                showAppTxtMsgMessage.setAppTxtMsgMessage((AppTxtMsgMessage)message.getContent());
                showAppTxtMsgMessage.setShowToast(true);
                EventBus.getDefault().post(showAppTxtMsgMessage);

            }else
            {
                ShowAppTxtMsgMessage showAppTxtMsgMessage=new ShowAppTxtMsgMessage();
                showAppTxtMsgMessage.setAppTxtMsgMessage((AppTxtMsgMessage)message.getContent());
                EventBus.getDefault().post(showAppTxtMsgMessage);
            }

        }else if (message.getContent() instanceof ImageMessage) {

            final ImageMessage imageMessage = (ImageMessage) message.getContent();
            Log.d("onReceived", "ImageMessage--收收收收--接收到一条【图片消息】---ThumUri--" + imageMessage.getLocalUri());
            Log.d("onReceived", "ImageMessage--收收收收--接收到一条【图片消息】----Uri--" + imageMessage.getRemoteUri());


        } else if (message.getContent() instanceof VoiceMessage) {

            final VoiceMessage voiceMessage = (VoiceMessage) message.getContent();
            Log.d("onReceived", "VoiceMessage--收收收收--接收到一条【语音消息】-----" + voiceMessage.getUri());
            Log.e("onReceived", "VoiceMessage--收收收收--接收到一条【语音消息】 voiceMessage.getExtra-----" + voiceMessage.getExtra());

        } else if (message.getContent() instanceof ContactNotificationMessage) {
            ContactNotificationMessage mContactNotificationMessage = (ContactNotificationMessage) message.getContent();
            Log.d("onReceived", "ContactNotificationMessage--收收收收--接收到一条【联系人（好友）操作通知消息】-----" + mContactNotificationMessage.getMessage() + ",getExtra:" + mContactNotificationMessage.getExtra());

        } else if (message.getContent() instanceof ProfileNotificationMessage) {
            ProfileNotificationMessage mProfileNotificationMessage = (ProfileNotificationMessage) message.getContent();
            Log.d("onReceived", "ProfileNotificationMessage--收收收收--接收到一条【资料变更通知消息】-----" + mProfileNotificationMessage.getData() + ",getExtra:" + mProfileNotificationMessage.getExtra());

        } else if (message.getContent() instanceof CommandNotificationMessage) {
            CommandNotificationMessage mCommandNotificationMessage = (CommandNotificationMessage) message.getContent();
            Log.d("onReceived", "CommandNotificationMessage--收收收收--接收到一条【命令通知消息】-----" + mCommandNotificationMessage.getData() + ",getName:" + mCommandNotificationMessage.getName());
        } else if (message.getContent() instanceof InformationNotificationMessage) {
            InformationNotificationMessage mInformationNotificationMessage = (InformationNotificationMessage) message.getContent();
            Log.d("onReceived", "InformationNotificationMessage--收收收收--接收到一条【小灰条消息】-----" + mInformationNotificationMessage.getMessage() + ",getName:" + mInformationNotificationMessage.getExtra());

        }
        MessageContent messageContent=message.getContent();
        if (null!=messageContent&&(messageContent instanceof TextMessage||messageContent instanceof VoiceMessage||messageContent instanceof ImageMessage))
        {
            EventBus.getDefault().post(new QueryUnReadCountEvent(message.getTargetId()));
        }
        return false;
    }

    /***
     * 当点击会话头像后执行。
     */
    @Override
    public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String s) {
        return false;
    }

    /**
     * 长按会话头像后执行
     */
    @Override
    public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String s) {
        return false;
    }

    /**
     * 长按会话列表中的 item 时执行。
     */
    @Override
    public boolean onConversationLongClick(Context context, View view, UIConversation uiConversation) {
        return false;
    }

    /**
     * 点击会话列表中的 item 时执行。
     */
    @Override
    public boolean onConversationClick(Context context, View view, UIConversation uiConversation) {
        return false;
    }

    /**
     * 当点击用户头像后执行
     */
    @Override
    public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
        if (conversationType == Conversation.ConversationType.CUSTOMER_SERVICE || conversationType == Conversation.ConversationType.PUBLIC_SERVICE || conversationType == Conversation.ConversationType.APP_PUBLIC_SERVICE) {
            return false;
        }
        return true;
    }

    /**
     * 当长按用户头像后执行
     */
    @Override
    public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
        return false;
    }

    /**
     * 当点击消息时执行
     */
    @Override
    public boolean onMessageClick(Context context, View view, Message message) {

        /**
         * 实时位置分享
         * */
        if (message.getContent() instanceof RealTimeLocationStartMessage) {


        }

        /**
         * 位置分享
         * */
        if (message.getContent() instanceof LocationMessage) {

        }
        return false;
    }

    /**
     * 当点击链接消息时执行
     */
    @Override
    public boolean onMessageLinkClick(Context context, String s) {
        return false;
    }

    /**
     * 当长按消息时执行
     */
    @Override
    public boolean onMessageLongClick(Context context, View view, Message message) {
        return false;
    }

    @Override
    public void onChanged(ConnectionStatus connectionStatus) {
        switch (connectionStatus) {

            case CONNECTED://连接成功。

                break;
            case DISCONNECTED://断开连接。

                break;
            case CONNECTING://连接中。

                break;
            case NETWORK_UNAVAILABLE://网络不可用。

                break;
            case KICKED_OFFLINE_BY_OTHER_CLIENT://用户账户在其他设备登录，本机会被踢掉线
                Log.i(ShouerAppContext.class.getSimpleName(), "当前线程:" + Thread.currentThread().getName());
                if (((App) mContext.getApplicationContext()).isUserLogin()) {
                    ((App) mContext.getApplicationContext()).loginOutSavePass();
                    EventBus.getDefault().post(new RongRemoteLoginEvent());
                }
                break;
        }
    }
}
